package com.monitor.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 代理检测器，用于检测和阻止代理服务器的使用
 */
public class ProxyDetector {
    private List<String> knownProxyProcesses;
    private boolean enabled;
    
    public ProxyDetector() {
        this.knownProxyProcesses = new ArrayList<>();
        this.enabled = true;
        initKnownProxyProcesses();
    }
    
    private void initKnownProxyProcesses() {
        // 添加已知的代理软件进程名称
        knownProxyProcesses.add("proxifier.exe");
        knownProxyProcesses.add("tor.exe");
        knownProxyProcesses.add("privoxy.exe");
        knownProxyProcesses.add("psiphon.exe");
        knownProxyProcesses.add("ultrasurf.exe");
        knownProxyProcesses.add("freegate.exe");
        knownProxyProcesses.add("lantern.exe");
        knownProxyProcesses.add("shadowsocks.exe");
        knownProxyProcesses.add("v2ray.exe");
        // 可以根据需要添加更多
    }
    
    /**
     * 检测系统是否正在使用代理
     * @return 如果检测到代理返回true，否则返回false
     */
    public boolean isProxyInUse() {
        if (!enabled) {
            return false;
        }
        
        // 检查系统代理设置
        boolean systemProxyDetected = checkSystemProxy();
        
        // 检查已知代理进程
        boolean proxyProcessDetected = checkProxyProcesses();
        
        // 检查网络连接特征
        boolean networkProxyDetected = checkNetworkProxy();
        
        return systemProxyDetected || proxyProcessDetected || networkProxyDetected;
    }
    
    /**
     * 检查系统代理设置
     * @return 如果检测到系统代理返回true，否则返回false
     */
    private boolean checkSystemProxy() {
        // 获取系统代理设置
        String httpProxy = System.getProperty("http.proxyHost");
        String httpsProxy = System.getProperty("https.proxyHost");
        String socksProxy = System.getProperty("socksProxyHost");
        
        return httpProxy != null || httpsProxy != null || socksProxy != null;
    }
    
    /**
     * 检查是否有已知的代理进程在运行
     * @return 如果检测到代理进程返回true，否则返回false
     */
    private boolean checkProxyProcesses() {
        try {
            Process process;
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                process = Runtime.getRuntime().exec("tasklist /fo csv /nh");
            } else {
                process = Runtime.getRuntime().exec("ps -e");
            }
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                for (String proxyProcess : knownProxyProcesses) {
                    if (line.toLowerCase().contains(proxyProcess.toLowerCase())) {
                        reader.close();
                        return true;
                    }
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    /**
     * 检查网络连接特征是否表明使用了代理
     * @return 如果检测到网络代理返回true，否则返回false
     */
    private boolean checkNetworkProxy() {
        try {
            // 尝试连接到一个已知的服务器，检查响应头中是否有代理特征
            URL url = new URL("http://www.example.com");
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.connect();
            
            // 检查响应头
            String via = conn.getHeaderField("Via");
            String xForwardedFor = conn.getHeaderField("X-Forwarded-For");
            String proxyConnection = conn.getHeaderField("Proxy-Connection");
            
            return via != null || xForwardedFor != null || proxyConnection != null;
            
        } catch (IOException e) {
            // 连接失败，可能是网络问题或代理问题
            return false;
        }
    }
    
    /**
     * 尝试阻止代理连接
     * @return 如果成功阻止返回true，否则返回false
     */
    public boolean blockProxyConnection() {
        if (!enabled) {
            return false;
        }
        
        boolean success = false;
        
        // 尝试终止已知的代理进程
        if (checkProxyProcesses()) {
            success = terminateProxyProcesses();
        }
        
        // 尝试重置系统代理设置
        if (checkSystemProxy()) {
            success = resetSystemProxy() || success;
        }
        
        return success;
    }
    
    /**
     * 终止已知的代理进程
     * @return 如果成功终止任何进程返回true，否则返回false
     */
    private boolean terminateProxyProcesses() {
        boolean anyTerminated = false;
        
        try {
            for (String proxyProcess : knownProxyProcesses) {
                if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                    Process process = Runtime.getRuntime().exec("taskkill /F /IM " + proxyProcess);
                    int exitCode = process.waitFor();
                    if (exitCode == 0) {
                        anyTerminated = true;
                    }
                } else {
                    Process process = Runtime.getRuntime().exec("pkill -f " + proxyProcess);
                    int exitCode = process.waitFor();
                    if (exitCode == 0) {
                        anyTerminated = true;
                    }
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        
        return anyTerminated;
    }
    
    /**
     * 重置系统代理设置
     * @return 如果成功重置返回true，否则返回false
     */
    private boolean resetSystemProxy() {
        try {
            if (System.getProperty("os.name").toLowerCase().contains("windows")) {
                // 在Windows上重置代理设置
                Process process = Runtime.getRuntime().exec("reg add \"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\" /v ProxyEnable /t REG_DWORD /d 0 /f");
                return process.waitFor() == 0;
            } else {
                // 在其他系统上重置代理设置（这里简化处理）
                System.setProperty("http.proxyHost", "");
                System.setProperty("https.proxyHost", "");
                System.setProperty("socksProxyHost", "");
                return true;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 添加已知的代理进程名称
     * @param processName 进程名称
     */
    public void addKnownProxyProcess(String processName) {
        if (processName != null && !processName.isEmpty() && !knownProxyProcesses.contains(processName)) {
            knownProxyProcesses.add(processName);
        }
    }
    
    /**
     * 获取已知的代理进程列表
     * @return 代理进程列表
     */
    public List<String> getKnownProxyProcesses() {
        return new ArrayList<>(knownProxyProcesses);
    }
    
    /**
     * 启用代理检测
     */
    public void enable() {
        this.enabled = true;
    }
    
    /**
     * 禁用代理检测
     */
    public void disable() {
        this.enabled = false;
    }
    
    /**
     * 检查代理检测是否启用
     * @return 如果启用返回true，否则返回false
     */
    public boolean isEnabled() {
        return enabled;
    }
}